<?php
namespace Mp\Service\Form;

use Closure;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Support\Fluent;
use Mp\Service\Widget\Widget;

class Form extends fluent implements Renderable{

	protected $action;

	protected $enctype = 'application/x-www-form-urlencoded';

	protected $method = 'POST';

	public $widgets = [];

	public $view = 'Mp::form.form';

	public $data = [];

	private function addWidget(Widget $widget){
		array_push($this->widgets,$widget);
	}

	public function widget($content){

		if($content instanceof Closure){
			$widget = call_user_func($content);
			$this->addWidget($widget);
		}elseif($content instanceof Widget){	
			$this->addWidget($content);
		}

		return $this;
	}

	public function action($action ){
		$this->action = $action;
	}

	public function form(Closure $content){

		call_user_func($content , $this);
		return $this;
	}

	public function view($view){
		$this->view = $view;
	}

	public function render(){
		$this->data = [
			'action' => $this->action,
			'method' => $this->method,
			'enctype' => $this->enctype,
			'widgets' => $this->widgets,
		];
		return view($this->view,$this->data);
	}

	public function __toString(){

		return $this->render();
	}


}